Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,,,_]
static void Main(string[] args)
{
RemoveElement();
}
private static void RemoveElement()
{
var nums = new int[] { 3, 2, 2, 3,};
int val = 3;
int length = RemoveElement(nums, val);
Console.WriteLine($"新的長度:{length}");
Console.ReadKey();
}
private static int RemoveElement(int[] nums, int val)
{
int index = 0;
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] != val)
{
nums[index] = nums[i];
index += 1;
}
}
return index;
}
LeetCode 27
JavaScript:
nums = [0,1,2,2,3,0,4,2]
val = 2
const result = nums.filter(item=> item !== val).length // 5